package com.rd.student.dashuju.zhengchengxiang.day0728;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class Randomizer {
    /**
     * 编写一个随机器，先通过文件，如“all.txt”读取班级所有同学的名字，
     * 然后根据输入的个数n，随机出不重复的n个同学，
     * 再通过另一个文件，如“random.txt”保存随机后的同学名字。
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入个数：");
        int i = scanner.nextInt();
        // 人数37人
        if (i > 0 && i < 38) {
            randomizer(i);
        } else {
            System.out.println("输入不正确");
        }

    }

    public static void randomizer(int n) throws Exception {
        // 读取文件
        RandomAccessFile file = new RandomAccessFile("all.txt", "rw");
        OutputStream os = new BufferedOutputStream(new FileOutputStream("random.txt"));
        file.seek(0);
        byte[] arr = new byte[1024];
        file.read(arr);
        String str = new String(arr);
        System.out.println("所有同学：" + str);
        // set自动去除重复元素
        Set<String> list = new HashSet<>();
        String[] split = str.split("、");
        String ss = "";
        Random random = new Random();
        while (list.size() < n) {
            int index = random.nextInt(split.length);
            String name = split[index];
            if (!list.contains(name)) {
                list.add(name);
                ss = ss + name + " ";
            }
        }
        System.out.println("随机选择" + n + "个学生：" + list);
        byte[] bytes = ss.getBytes();
        os.write(bytes);

        // 关闭
        os.close();
        file.close();
    }
}
